// page/component/new-pages/cart/cart.js
const db = wx.cloud.database()
var uid = wx.getStorageSync('openid');
// var i = 0;
Page({
  data: {
    cart: [], // 购物车列表
    hasList: false, // 列表是否有数据
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: false, // 全选状态，默认不全选
    obj: {
      name: "hello"
    },
    toBuy: []
  },
  async onShow() {
    console.log("show")
    this.setData({
      hasList: false
    })
    this.setData({
      totalPrice:0
    })
    var pids = [];
    var num = [];
    var cart = [];
    var cartId = "";
    var that = this;
    var j = 0
    var i = 0;
    await db.collection("cart").where({
        uid: this.uid
      })
      .get().then(res => {
        cartId = res.data[0]._id;
        res.data[0].pids.forEach(item => {
          pids.push(item.id)
          num.push(item.num)

        })
        that.setData({
          cartId: cartId
        })
      })
    for (var x = 0; x < pids.length; x++) {
      await db.collection("product").where({
          _id: pids[x]
        })
        .get().then(res => {
          console.log(res)
          var {
            _id,
            pname,
            picUrl,
            price
          } = res.data[0];
          cart.push({
            _id,
            pname,
            picUrl,
            price,
            num: num[j],
            no: i,
          })
          i = i + 1;
          j = j + 1
          console.log(cart)
          console.log(this.data.cart)
        })
    }
    that.setData({
      cart
    })
    if (cart.length != 0) {
      this.setData({
        hasList: true
      })
    }
  },

  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    console.log(index)
    let cart = this.data.cart;
    const selected = cart[index].selected;
    cart[index].selected = !selected;
    console.log(cart[index].selected)
    this.setData({
      cart: cart
    });
    this.getTotalPrice();
  },

  /**
   * 删除购物车当前商品
   */
  deleteList(options) {
    var id = options.currentTarget.dataset.id;
    console.log(id)
    var that = this;
    var i = 0;
    var no = options.currentTarget.dataset.no;;
    console.log(no)
    // console.log(id)
    var cart = that.data.cart;
    // console.log(cart)
    cart.splice(no, 1);
    // console.log("序号改变")
    cart.forEach(item => {
      item.no = i;
      i = i + 1;
      // console.log(item.no)
    })
    // console.log(cart)
    that.setData({
      cart
    })
    //删除云数据库中的数据
    console.log(id)
    wx.cloud.callFunction({
      name: "delPro",
      data: {
        pids: id,
        uid:wx.getStorageSync('openid')
      }
    })
    if (!cart.length) {
      this.setData({
        hasList: false
      });
    } else {
      this.getTotalPrice();
    }
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let cart = this.data.cart;

    for (let i = 0; i < cart.length; i++) {
      cart[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      cart: cart
    });
    this.getTotalPrice();
  },

  /**
   * 绑定加数量事件
   */
  async addCount(options) {
    var that = this;
    var num = 0;
    var no = 0;
    var cart = that.data.cart;
    num = options.currentTarget.dataset.num;
    no = options.currentTarget.dataset.no;
    num = num + 1;
    cart[no].num = num;
    that.setData({
      cart
    })

    // 修改数据库
    var cartId = "";
    cartId = that.data.cartId;
    var id = that.data.cart[no]._id
    console.log(id)
    // 更新购物车云函数
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.cloud.callFunction({
      name: "update",
      data: {
        num: num,
        no: no,
        cartId: cartId,
        id: id,
      },
    }).then(res => {
      setTimeout(function () {
        wx.hideLoading()
      }, 500)
    })
  },

  /**
   * 绑定减数量事件
   */
  async minusCount(options) {
    var that = this;
    var num = 0;
    var no = 0;
    var cart = that.data.cart;
    num = options.currentTarget.dataset.num;
    no = options.currentTarget.dataset.no;
    if (num > 1) {
      num = num - 1;
      cart[no].num = num;
      that.setData({
        cart
      })

      // 修改数据库
      var cartId = "";
      cartId = that.data.cartId;
      var id = that.data.cart[no]._id
      console.log(id)
      // 更新购物车云函数
      wx.showLoading({
        title: '加载中',
        mask: true,
      })
      wx.cloud.callFunction({
        name: "update",
        data: {
          num: num,
          no: no,
          cartId: cartId,
          id: id,
        },
      }).then(res => {
        setTimeout(function () {
          wx.hideLoading()
        }, 500)
      })
    } else {
      wx.showModal({
        cancelColor: 'red',
        content: "无法再减少数量"
      })
    }
  },

  packGoods() {
    console.log(this.data.cart[0].selected)
    var toBuy = []
    for (var x = 0; x < this.data.cart.length; x++) {
      if (this.data.cart[x].selected) {
        toBuy.push(this.data.cart[x])
      }
    }
    console.log(toBuy)
    if(toBuy.length != 0){
    wx.setStorageSync('toBuy', toBuy)
    wx.navigateTo({
      url: '../orders/orders',
    })
    }else{
      wx.showModal({
        cancelColor: 'red',
        content:'您没有选择任何商品'
      })
    }
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let cart = this.data.cart; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < cart.length; i++) { // 循环列表得到每个数据
      if (cart[i].selected) { // 判断选中才会计算价格
        total += cart[i].num * cart[i].price; // 所有价格加起来
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      cart: cart,
      totalPrice: total.toFixed(2)
    });
  },
  
})